import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:redbook_app/api.dart';
import 'package:redbook_app/pages/VideoDownloader.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final _controller = TextEditingController();
  String _clipboardText = ''; // 存储读取的剪贴板内容
  String server_url = "";

  // 读取剪贴板内容
  Future<void> _pasteFromClipboard() async {
    ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
    if (data != null && data.text != null) {
      setState(() {
        _clipboardText = data.text!;
        _controller.text = _clipboardText; // 将剪贴板内容填入输入框
      });
    } else {
      setState(() {
        _clipboardText = '剪贴板中没有文本';
      });
    }
  }

  Future<void> _loadSetting() async {
    final prefs = await SharedPreferences.getInstance();
    var serverUrl = prefs.getString("server_url") ?? "";
    print(serverUrl);
    setState(() {
      server_url = serverUrl;
    });
  }

  Future<void> _tapDownloadVideo() async {
    if (_controller.text.isEmpty) {
      Fluttertoast.showToast(
          msg: "下载链接不能为空",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.TOP,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red[300],
          textColor: Colors.white,
          fontSize: 14.0);
      return;
    }
    if (server_url.isEmpty) {
      Fluttertoast.showToast(
          msg: "服务地址不能为空",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.TOP,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red[300],
          textColor: Colors.white,
          fontSize: 14.0);
      return;
    }

    var url = Uri.parse(server_url + (API["START_JOB"] ?? ""));
    try {
      final resp = await http.post(url,
          headers: {
            'Content-Type': 'application/json',
          },
          body: jsonEncode({"url": _controller.text}));
      var rdata = jsonDecode(resp.body);

      if (rdata["code"] == 500) {
        throw Exception(rdata["message"]);
      }
      Fluttertoast.showToast(
          msg: "已加入下载队列",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.TOP,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.green[300],
          textColor: Colors.white,
          fontSize: 14.0);
    } catch (e) {
      Fluttertoast.showToast(
          msg: e.toString(),
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.TOP,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red[300],
          textColor: Colors.white,
          fontSize: 14.0);
    }
  }

  Future<void> _requestStoragePermission() async {
    var status = await Permission.manageExternalStorage.status;
    print("============");
    print(status);
    if (!status.isGranted) {
      status = await Permission.manageExternalStorage.request();
    }

    if (status.isGranted) {
      print("所有文件访问权限已授予");
      // 执行存储相关操作
    } else if (status.isDenied) {
      print("权限被拒绝");
    } else if (status.isPermanentlyDenied) {
      print("权限被永久拒绝，请前往设置开启");
      openAppSettings(); // 引导用户到设置页面
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _loadSetting();
    _requestStoragePermission();
  }

  @override
  Widget build(BuildContext context) {
    print("home build");
    return Scaffold(
      body: Container(
        padding: EdgeInsets.only(top: 100, left: 10, right: 10),
        decoration: BoxDecoration(color: Colors.white),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            TextField(
              controller: _controller,
              style: TextStyle(fontSize: 12),
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                hintText: '请输入要下载的链接',
                prefixIcon: Icon(Icons.link),
              ),
              keyboardType: TextInputType.multiline,
              minLines: 4,
              maxLines: 4,
            ),
            SizedBox(
              height: 20,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                SizedBox(
                  width: 100,
                  child: ElevatedButton(
                      style: ElevatedButton.styleFrom(backgroundColor: Colors.green, foregroundColor: Colors.white),
                      onPressed: _pasteFromClipboard,
                      child: Text("粘贴")),
                ),
                SizedBox(
                  width: 100,
                  child: ElevatedButton(onPressed: () => {_controller.text = ""}, child: Text("清空")),
                ),
                SizedBox(
                  width: 100,
                  child: ElevatedButton(
                      style: ElevatedButton.styleFrom(backgroundColor: Colors.purple, foregroundColor: Colors.white),
                      onPressed: _tapDownloadVideo,
                      child: Text("下载")),
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.only(top: 30),
              width: double.infinity,
              child: ElevatedButton(
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.green, foregroundColor: Colors.white),
                  onPressed: () => {Navigator.pushNamed(context, "/download")},
                  child: Text("下载列表")),
            ),
            Container(
              padding: EdgeInsets.only(top: 30),
              width: double.infinity,
              child: ElevatedButton(
                  onPressed: () async {
                    final result = await Navigator.pushNamed(context, "/setting");
                    // print("返回了");
                    _loadSetting();
                  },
                  child: Text("系统配置")),
            )
          ],
        ),
      ),
    );
  }
}
